package com.health.ts.controller;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.health.ts.constant.ApiResult;
import com.health.ts.entity.sysmanage.LoginBodyVo;
import com.health.ts.exception.BusinessException;
import com.wf.captcha.utils.CaptchaUtil;
/**
 * 登录与登出
 * @author Administrator
 */
@RestController
@RequestMapping(value = "/api",produces= BaseController.JSON_UTF8)
public class LoginController extends BaseController{
	 
	/**
	 * 登录验证
	 * @param user
	 * @return
	 */
	@PostMapping(value="/login")
	public ApiResult login(@RequestBody @Validated LoginBodyVo loginUser, HttpServletRequest request){
	    String userName=loginUser.getUserName();
	    String passWord=loginUser.getPassword();
	    String captcha=loginUser.getCaptcha();
        if(!CaptchaUtil.ver(captcha,request)){
        	// 清除session中的验证码
//        	CaptchaUtil.clear(request);
        	throw new BusinessException("验证码错误");
        }
	    try {
            UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
            SecurityUtils.getSubject().login(token);
        } catch (IncorrectCredentialsException ice) {
        	throw new BusinessException("密码错误");
        } catch (UnknownAccountException uae) {
	    	throw new BusinessException("账号不存在");
        } 
	    return ApiResult.success();
	 }
}
